import { defineStore } from 'pinia'
import { getUserInfo, login, logout, wxLogin } from '../api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: null,
    isLoggedIn: !!localStorage.getItem('token') // 根据Token判断登录状态
  }),
  
  getters: {
    username: (state) => state.userInfo?.username || '',
    avatar: (state) => state.userInfo?.avatar || ''
  },
  
  actions: {
    // 设置Token
    setToken(token) {
      this.token = token
      localStorage.setItem('token', token)
      this.isLoggedIn = true
    },
    
    // 清除Token
    clearToken() {
      this.token = ''
      localStorage.removeItem('token')
      this.isLoggedIn = false
      this.userInfo = null
    },
    
    // 获取用户信息
    async fetchUserInfo() {
      try {
        const res = await getUserInfo()
        if (res.code === 0) {
          this.userInfo = res.data
          return res.data
        }
        return null
      } catch (error) {
        console.error('获取用户信息失败', error)
        return null
      }
    },
    
    // 用户登录
    async userLogin(loginForm) {
      try {
        const res = await login(loginForm)
        if (res.code === 0) {
          this.setToken(res.data.token)
          await this.fetchUserInfo()
          return true
        }
        return false
      } catch (error) {
        console.error('登录失败', error)
        return false
      }
    },
    
    // 微信登录
    async wechatLogin(code) {
      try {
        const res = await wxLogin(code)
        if (res.code === 0) {
          this.setToken(res.data.token)
          await this.fetchUserInfo()
          return true
        }
        return false
      } catch (error) {
        console.error('微信登录失败', error)
        return false
      }
    },
    
    // 用户登出
    async userLogout() {
      try {
        await logout()
        this.clearToken()
        return true
      } catch (error) {
        console.error('登出失败', error)
        return false
      }
    }
  }
})
